package com.smartcampusbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smartcampusbackend.mapper.PaymentOrderMapper;
import com.smartcampusbackend.mapper.UserMapper;
import com.smartcampusbackend.mapper.MajorMapper;
import com.smartcampusbackend.model.PaymentOrder;
import com.smartcampusbackend.model.User;
import com.smartcampusbackend.model.Major;
import com.smartcampusbackend.service.PaymentOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.UUID;

@Service
public class PaymentOrderServiceImpl implements PaymentOrderService {
    
    @Autowired
    private PaymentOrderMapper paymentOrderMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private MajorMapper majorMapper;
    
    @Override
    public PaymentOrder createOrder(PaymentOrder order) {
        order.setOrderNo(generateOrderNo());
        order.setStatus("pending");
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        paymentOrderMapper.insert(order);
        return order;
    }
    
    @Override
    public boolean payOrder(String orderNo, String payMethod) {
        PaymentOrder order = paymentOrderMapper.selectOne(
            new QueryWrapper<PaymentOrder>().eq("order_no", orderNo)
        );
        if (order != null && "pending".equals(order.getStatus())) {
            order.setStatus("paid");
            order.setPayMethod(payMethod);
            order.setPayTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            paymentOrderMapper.updateById(order);
            return true;
        }
        return false;
    }
    
    @Override
    public boolean cancelOrder(String orderNo) {
        PaymentOrder order = paymentOrderMapper.selectOne(
            new QueryWrapper<PaymentOrder>().eq("order_no", orderNo)
        );
        if (order != null && "pending".equals(order.getStatus())) {
            order.setStatus("cancelled");
            order.setUpdateTime(LocalDateTime.now());
            paymentOrderMapper.updateById(order);
            return true;
        }
        return false;
    }
    
    @Override
    public PaymentOrder getOrderByOrderNo(String orderNo) {
        return paymentOrderMapper.selectOne(
            new QueryWrapper<PaymentOrder>().eq("order_no", orderNo)
        );
    }
    
    @Override
    public List<PaymentOrder> getUserOrders(Integer userId, String year, String category, String userRole) {
        QueryWrapper<PaymentOrder> queryWrapper = new QueryWrapper<>();
        
        // 根据角色控制查询范围
        if ("ADMIN".equals(userRole)) {
            // 管理员可以查看所有订单
        } else {
            // 其他角色只能查看自己的订单
            queryWrapper.eq("user_id", userId);
        }
        
        if (year != null && !year.trim().isEmpty()) {
            queryWrapper.eq("year", year);
        }
        
        if (category != null && !category.trim().isEmpty()) {
            queryWrapper.eq("category", category);
        }
        
        queryWrapper.orderByDesc("create_time");
        return paymentOrderMapper.selectList(queryWrapper);
    }
    
    @Override
    public List<PaymentOrder> getAllOrders(String year, String category, String username) {
        QueryWrapper<PaymentOrder> queryWrapper = new QueryWrapper<>();
        
        if (year != null && !year.trim().isEmpty()) {
            queryWrapper.eq("year", year);
        }
        
        if (category != null && !category.trim().isEmpty()) {
            queryWrapper.eq("category", category);
        }
        
        if (username != null && !username.trim().isEmpty()) {
            // 通过用户名查找用户ID
            User user = userMapper.selectOne(
                new QueryWrapper<User>().eq("username", username)
            );
            if (user != null) {
                queryWrapper.eq("user_id", user.getId());
            }
        }
        
        queryWrapper.orderByDesc("create_time");
        return paymentOrderMapper.selectList(queryWrapper);
    }
    
    @Override
    public Map<String, BigDecimal> getStudentFees(Integer userId) {
        Map<String, BigDecimal> fees = new HashMap<>();
        
        // 获取用户信息
        User user = userMapper.selectById(userId);
        if (user == null || !"STUDENT".equals(user.getRole()) || user.getMajorId() == null) {
            return fees;
        }
        
        // 获取专业信息
        Major major = majorMapper.selectById(user.getMajorId());
        if (major != null) {
            fees.put("tuition", major.getTuitionFee() != null ? major.getTuitionFee() : BigDecimal.ZERO);
            fees.put("accommodation", major.getAccommodationFee() != null ? major.getAccommodationFee() : BigDecimal.ZERO);
        }
        
        return fees;
    }
    
    @Override
    public boolean validateStudentMajor(Integer userId) {
        User user = userMapper.selectById(userId);
        if (user == null || !"STUDENT".equals(user.getRole())) {
            return false;
        }
        
        // 检查学生是否有专业信息
        if (user.getMajorId() == null) {
            return false;
        }
        
        // 检查专业是否存在
        Major major = majorMapper.selectById(user.getMajorId());
        return major != null;
    }
    
    private String generateOrderNo() {
        return  System.currentTimeMillis() + "";
    }
} 